package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import entity.MonthlyCard;
import entity.PassBill;
import main.Main;
import util.Constants;
import util.Validator;

public class LeaveJPanel extends JPanel {
	private static final long serialVersionUID = -1464040524610072378L;

	public LeaveJPanel(){
        setLayout(null);
        setBorder(BorderFactory.createTitledBorder("离场"));
        initUI();
	}
	
	private void initUI(){
		
		JLabel lab1 = new JLabel("车牌号",SwingConstants.RIGHT);
		lab1.setFont(Constants.font);
		lab1.setBounds(100, 30, 60, 30);
	        
        JTextField lab1input = new JTextField();
        Validator.bind(lab1input,Validator.CARID);
        lab1input.setBounds(165, 30, 120, 30);
                
		JButton btn = new JButton("离场");
		btn.setBounds(165, 90, 60, 30);
		btn.setFont(Constants.font);
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String lab1inputStr = lab1input.getText().trim();

				if (Validator.isEmpty(lab1inputStr)) {
					JOptionPane.showMessageDialog(null, "请输入车牌号！");
					return;
				}
				
				boolean result = false;
				PassBill bill = new PassBill();
				if(bill.checkStock(lab1inputStr)){
					MonthlyCard card = new MonthlyCard();
					if(card.check(lab1inputStr)){
						result = bill.leave();
						if (result) {
							JOptionPane.showMessageDialog(null, "操作成功！");
						}else{
							JOptionPane.showMessageDialog(null, "操作失败！");
						}
					}else{
						JDialog dlg = new JDialog(Main.frame, "停车账单", true);
						Main.dlgStack.push(dlg);
						dlg.setSize(450, 500);
						dlg.setLocationRelativeTo(null);
						dlg.add(new AddParkReceiptJPanel(bill));
						dlg.validate();
						dlg.addWindowListener(new WindowAdapter() {
				        	@Override
				            public void windowClosing(WindowEvent e) {
				        		if(Main.dlgStack.size() == 1){
				        			Main.dlgStack.pop().dispose();
				        		}
				            }
						});
						dlg.setVisible(true);
					}
				}else{
					JOptionPane.showMessageDialog(null, "操作失败,系统无入场记录，请人工出场！");
				}
			}
		});
		
		add(lab1);
		add(lab1input);
		add(btn);
	}
}
